﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Configuration;

public partial class UserControls_GalleryFoldersUC : System.Web.UI.UserControl
{
    public int DisplayCount { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadFolders();
    }

    private string hiddenExtensionFolder = ConfigurationManager.AppSettings["HiddenExtensionFolder"];
    private void LoadFolders()
    {
        string[] folderPaths = ConfigurationManager.AppSettings["GalleryFolders"].Split(';');
        DataTable foldersDT = new DataTable();
        foldersDT.Columns.Add("Name", typeof(string));
        foldersDT.Columns.Add("FolderPath", typeof(string));
        foldersDT.Columns.Add("Created", typeof(DateTime));

        foreach (string folderPath in folderPaths)
        {
            string serverFolderPath = Server.MapPath(folderPath);
            if (Directory.Exists(serverFolderPath))
            {
                DirectoryInfo di = new DirectoryInfo(serverFolderPath);
                foreach (DirectoryInfo folderInfo in di.GetDirectories())
                {
                    if (!folderInfo.Name.ToLower().EndsWith(hiddenExtensionFolder))
                    {
                        DataRow dr = foldersDT.NewRow();
                        dr["Name"] = folderInfo.Name;
                        dr["FolderPath"] = folderPath + folderInfo.Name;
                        dr["Created"] = folderInfo.CreationTime;
                        foldersDT.Rows.Add(dr);
                    }
                }
            }
        }

        foldersDT.DefaultView.Sort = "Name DESC";
        foldersDT = foldersDT.DefaultView.ToTable();

        if (DisplayCount > 0
            && foldersDT.Rows.Count > DisplayCount)
        {
            //Delete rest of the rows
            int initialRowsNumber = foldersDT.Rows.Count;
            for (int i = 0; i < initialRowsNumber - DisplayCount; i++)
            {
                foldersDT.Rows.RemoveAt(foldersDT.Rows.Count - 1);
            }
        }

        rptGalleryFolders.DataSource = foldersDT;
        rptGalleryFolders.DataBind();
    }
}